#include <QMutexLocker>
#include <QDir>
#include <QApplication>
#include <QSettings>
#include <QDebug>

#include "qlslanguagesmanager.h"

/* static */
QMutex QLsLanguagesManager::m_instanceMutex;
QLsLanguagesManager *QLsLanguagesManager::m_instance = nullptr;

QLsLanguagesManager::QLsLanguagesManager(QObject *parent) : QObject(parent)
{
	m_langPacksList.clear();
	m_curLangPack.clear();
	m_curTranslator = nullptr;

	/* 初始化可用语言包列表 */
	RefreshLocalLangPacks();

	/* 初始化当前语言包 */
	QSettings settings("ini/langPacks.ini", QSettings::IniFormat);
	QString curLangPack = settings.value("cur/langPack", "lang_Chinese").toString();
	LoadLangPack(curLangPack);
}

/* 唯一实例 */
QLsLanguagesManager &QLsLanguagesManager::GetInstance()
{
	if(!m_instance)
	{
		QMutexLocker locker(&m_instanceMutex);
		if(!m_instance)
			m_instance = new QLsLanguagesManager;
	}
	return *m_instance;
}

/* 销毁实例 */
void QLsLanguagesManager::DestroyInstance()
{
	if(m_instance)
	{
		QMutexLocker locker(&m_instanceMutex);
		if(m_instance)
		{
			delete m_instance;
			m_instance = nullptr;
		}
	}
}

/* 刷新本地语言包 */
void QLsLanguagesManager::RefreshLocalLangPacks()
{
	/* 清空上次记录 */
	m_langPacksList.clear();

	/* 打开本地语言包文件夹 */
	QDir themesDir = QDir(qApp->applicationDirPath());
	if(!themesDir.cd("language")) return;
	foreach (QString filename, themesDir.entryList(QDir::Files))
	{
		/* 获取qm语言包文件 */
		if(!filename.endsWith(".qm")) continue;

		/* 加入列表 */
		m_langPacksList.push_back(filename.mid(0, filename.size() - 3));
	}
}

/* 加载语言包 */
bool QLsLanguagesManager::LoadLangPack(const QString &langPackName)
{
	/* 判断当前语言包是否存在 或 有无变化 */
	if(!m_langPacksList.contains(langPackName) || m_curLangPack == langPackName) return false;

	/* 判断语言包文件夹和判断当前语言包文件是否存在 */
	QDir langPacksDir = QDir(qApp->applicationDirPath());
	QString langPackFilename = QString("%1.qm").arg(langPackName);
	if(!langPacksDir.cd("language") || !langPacksDir.entryList().contains(langPackFilename)) return false;

	/* 加载语言包：先清空上次的 */
	if(m_curTranslator)
	{
		qApp->removeTranslator(m_curTranslator);
		delete m_curTranslator;
		m_curTranslator = nullptr;
	}
	QTranslator *translator = new QTranslator;
	if(!translator->load(langPackFilename, langPacksDir.absolutePath()))
	{
		delete translator;
		return false;
	}
	qApp->installTranslator(translator);
	m_curLangPack = langPackName;
	m_curTranslator = translator;

	/* 更新配置文件 */
	QSettings settings("ini/langPacks.ini", QSettings::IniFormat);
	settings.setValue("cur/langPack", langPackName);
	return true;
}

/* 获取可用语言包列表 */
QStringList QLsLanguagesManager::GetLangPacks() const
{
	return m_langPacksList;
}

/* 获取当前语言包 */
QString QLsLanguagesManager::GetCurrentLangPack() const
{
	return m_curLangPack;
}
